package com.bleeth.fx.helper;

import cn.hutool.json.JSONObject;
import javafx.collections.ObservableList;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.MapValueFactory;
import javafx.util.Callback;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Bleeth
 * @date ：2021-11-07
 * @description：表格工具
 */
public class TableHelper {


    public static TableBuilder builder() {
        TableBuilder builder = new TableBuilder();
        return builder;
    }


    public static class TableBuilder {

        private TableView tableView = new TableView();

        Map<String, TableColumn<JSONObject, String>> columnMap = new HashMap<>();

        public TableBuilder addTableColumn(String columnName) {
            TableColumn<JSONObject, String> column = new TableColumn<>(columnName);
            column.setCellValueFactory(new MapValueFactory(columnName));
            columnMap.put(columnName, column);
            tableView.getColumns().add(column);
            return this;
        }

        public TableBuilder addTableColumn(String columnName, double minWidth) {
            TableColumn<JSONObject, String> column = new TableColumn<>(columnName);
            column.setMinWidth(minWidth);
            column.setCellValueFactory(new MapValueFactory(columnName));
            columnMap.put(columnName, column);
            tableView.getColumns().add(column);
            return this;
        }

        public TableBuilder addTableColumn(String columnName, double minWidth, String bindKey) {
            TableColumn<JSONObject, String> column = new TableColumn<>(columnName);
            column.setMinWidth(minWidth);
            column.setCellValueFactory(new MapValueFactory(bindKey));
            columnMap.put(columnName, column);
            tableView.getColumns().add(column);
            return this;
        }

        public TableBuilder setCellFactory(String columnName, Callback<TableColumn<JSONObject, String>, TableCell<JSONObject, String>> callback) {
            TableColumn<JSONObject, String> column = columnMap.get(columnName);
            column.setCellFactory(callback);
            return this;
        }

        public TableBuilder setEditable(boolean editable) {
            tableView.setEditable(editable);
            return this;
        }

        public TableBuilder setItems(ObservableList<JSONObject> items) {
            tableView.setItems(items);
            return this;
        }

        public TableBuilder setPrefWidth(double value) {
            tableView.setPrefWidth(value);
            return this;
        }

        public TableView build() {
            return tableView;
        }

    }

}
